package com.zzyl.nursing.controller.member;

import com.github.pagehelper.PageHelper;
import com.zzyl.common.core.controller.BaseController;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.core.domain.R;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.dto.ReservationPageDto;
import com.zzyl.nursing.service.IReservationService;
import com.zzyl.nursing.vo.ReservationCountVo;
import com.zzyl.nursing.vo.ReservationPageVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 预约信息Controller
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/member/reservation")
@Api(tags =  "预约信息相关接口")
public class MemberReservationController extends BaseController {

    @Autowired
    private IReservationService reservationService;

    @GetMapping("/cancelled-count")
    @ApiOperation("查询取消预约数量")
    public R<Integer> getCancelledReservationCount() {
        Long userId = UserThreadLocal.getUserId();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startTime = now.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);
        int count = reservationService.getTodayCancelledCount(userId, startTime, endTime);

        return R.ok(count);
    }

    @PostMapping
    @ApiOperation("新增预约")
    public AjaxResult addReservation(@RequestBody Reservation reservation) {
        R<Integer> cancelledReservationCount = getCancelledReservationCount();
        Integer data = cancelledReservationCount.getData();
        if (data >= 3) {
            return error("今天预约次数已用完");
        }
        reservationService.saveReservation(reservation);
        return success();
    }

    @GetMapping("/countByTime")
    @ApiOperation("查询每个时间段剩余预约次数")
    public R<List<ReservationCountVo>> getReservationCountByTime(Long time) {
        List<ReservationCountVo> reservationVo = reservationService.getReservationCountByTime(time);
        return R.ok(reservationVo);
    }

    @GetMapping("/page")
    @ApiOperation("分页查询预约信息")
    public R<ReservationPageVo> getReservationPage(ReservationPageDto reservationPageDto) {
        ReservationPageVo reservationPage = reservationService.getReservationPage(reservationPageDto);
        return R.ok(reservationPage);
    }

    @PutMapping("/{id}/cancel")
    @ApiOperation("取消预约")
    public AjaxResult cancelReservation(@PathVariable Long id) {
        return toAjax(reservationService.updateReservationById(id));
    }
}